package com.web.spider.util;

import com.alibaba.fastjson.JSON;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author chencl
 * @Date 2019/8/29 16:58
 * @Version: 1.0
 * @Description
 */
public class HttpCrawler {
	private HttpClientContext context;
	private CloseableHttpClient httpClient;

	public HttpCrawler() {
		// 全局请求设置
		RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setSocketTimeout(10000).setConnectTimeout(10000).build();

		// 创建cookie store的本地实例
		CookieStore cookieStore = new BasicCookieStore();
		// 创建HttpClient上下文
		context = HttpClientContext.create();
		context.setCookieStore(cookieStore);
		// 创建一个HttpClient
		httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
				.setDefaultCookieStore(cookieStore).build();
	}

	public String postJSON(String url, Map<String, String> header, String jsonStr){
		HttpPost httpPost = new HttpPost(url);

		httpPost.addHeader("Content-Type", "application/json");
		setHeader(httpPost, header);

		StringEntity requestEntity = new StringEntity(jsonStr, "UTF-8");
		//设置请求体
		httpPost.setEntity(requestEntity);

		CloseableHttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpPost, context);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			if(HttpStatus.SC_OK != statusCode){
				return null;
			}
			return EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			// 关闭
		}
		return null;
	}

	public String postForm(String url, Map<String, String> header, Map<String, String> params){
		HttpPost httpPost = new HttpPost(url);
		//httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
		setHeader(httpPost, header);
		List<Header> l = context.getCookieSpec().formatCookies(context.getCookieStore().getCookies());
		System.out.println(l.get(0).getValue());
		//httpPost.addHeader("Cookie", l.get(0).getValue());

		CloseableHttpResponse httpResponse = null;
		try {
			setFormParam(httpPost, params);

			httpResponse = httpClient.execute(httpPost, context);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			if(HttpStatus.SC_OK != statusCode){
				return null;
			}
			return EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			// 关闭
		}
		return null;
	}

	public String get(String url, Map<String, String> header, Map<String, Object> params){
		HttpGet httpGet = new HttpGet(url);
		setHeader(httpGet, header);
		CloseableHttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpGet, context);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			if(HttpStatus.SC_OK != statusCode){
				return null;
			}
			return EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			// 关闭
		}
		return null;
	}

	private void setHeader(HttpRequestBase httpRequestBase, Map<String, String> header){
		if(null != httpRequestBase && null != header && header.size() > 0){
			for(Map.Entry<String, String> entry : header.entrySet()){
				httpRequestBase.addHeader(entry.getKey(), entry.getValue());
			}
		}
	}

	private void setFormParam(HttpPost httpPost, Map<String, String> params) throws UnsupportedEncodingException {
		if(null != httpPost && null != params){
			List<BasicNameValuePair> pair =new ArrayList<BasicNameValuePair>();
			for (Map.Entry<String,String> entry : params.entrySet()) {
				pair.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
			}
			httpPost.setEntity(new UrlEncodedFormEntity(pair));
		}
	}

	private void printCookieStore(CookieStore cookieStore){
		if(null != cookieStore){
			List<Cookie> cookies = cookieStore.getCookies();
			if(null != cookies && cookies.size() > 0){
				for(Cookie cookie : cookies){
					System.out.println(cookie.getName());
					System.out.println(cookie.getValue());
					System.out.println(cookie.getComment());
					System.out.println(cookie.getCommentURL());
					System.out.println(cookie.getDomain());
					System.out.println(cookie.getExpiryDate());
					System.out.println(cookie.getPath());
					System.out.println(cookie.getPorts());
					System.out.println(cookie.getVersion());
				}
			}
		}
	}
}
